package cn.iocoder.yudao.module.pi.api;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Objects;

/**
 * @author shaoxh
 * @version 1.0
 * @description:
 * @date 2025/8/8 11:47
 */
@Service
@Slf4j
public class BizApiLogSearchClient {

    /**
     * 发送get请求
     *
     * @param url 地址
     * @return
     */
    public String get(String url) {
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        return getResponseString(request);

    }

    /**
     * 发送post请求
     *
     * @param jsonBody 请求体
     * @param url      地址
     * @return
     */
    public String post(String jsonBody, String url) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(jsonBody, JSON);

        Request postRequest = new Request.Builder()
                .url(url)
                .post(requestBody)
                .header("Content-Type", "application/json")
                .build();

        return getResponseString(postRequest);
    }

    @Nullable
    private static String getResponseString(Request request) {
        // 创建OkHttpClient实例
        OkHttpClient client = new OkHttpClient();

        // 发送请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.error("请求发送失败:{}", response);
                return null;
            }

            // 获取响应体
            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            log.error("请求发送失败", e);
        }

        return null;
    }

}
